package net.csdn.business.notify.api.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.csdn.business.notify.common.config.TargetTypeConfig;
import net.csdn.business.notify.common.config.properties.SystemUserProperties;
import net.csdn.business.notify.common.constant.CommonConstants;
import net.csdn.business.notify.common.enums.ResultCodeEnum;
import net.csdn.business.notify.common.exception.BusinessException;
import net.csdn.business.notify.common.mapper.NotifyUserSettingMapper;
import net.csdn.business.notify.common.model.dto.*;
import net.csdn.business.notify.common.model.entity.NotifyTemplateSeting;
import net.csdn.business.notify.common.model.entity.NotifyUserSetting;
import net.csdn.business.notify.common.model.query.NotifyUserSettingQuery;
import net.csdn.business.notify.common.model.vo.*;
import net.csdn.business.notify.api.service.INotifyUserSettingService;
import net.csdn.business.notify.feign.SystemFeignClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 通知中心-用户通知配置Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-27
 */
@RefreshScope
@Service
public class NotifyUserSettingServiceImpl extends ServiceImpl<NotifyUserSettingMapper, NotifyUserSetting> implements INotifyUserSettingService
{

    @Autowired
    private TargetTypeConfig targetTypeConfig;
    @Autowired
    private SystemFeignClient systemFeignClient;
    @Autowired
    private SystemUserProperties systemUserProperties;
    private Map<String, UserTargetVO> targetTypeInfo=new HashMap<>();


    /**
     * 初始化用户配置相关
     */
    @PostConstruct
    public void init(){
        List<NotifyTargetVO> list=targetTypeConfig.getList();
        for (NotifyTargetVO targetVO:list){
            String type=targetVO.getType();
            String desc=targetVO.getDesc();
            List<NotifyActVO> act=targetVO.getAct();
            Map<String,String> acts=new HashMap<>();
            for (NotifyActVO actVO:act){
                String actCode=actVO.getCode();
                String actDesc=actVO.getDesc();
                acts.put(actCode,actDesc);
            }
            UserTargetVO userTargetVO=new UserTargetVO();
            userTargetVO.setDesc(desc);
            userTargetVO.setActs(acts);
            targetTypeInfo.put(type,userTargetVO);
        }
    }


    /**
     * 分页查询通知中心-用户通知配置列表
     *
     * @param query 通知中心-用户通知配置
     * @return 通知中心-用户通知配置
     */
    @Override
    public Page<NotifyUserSettingVO> findPageList(NotifyUserSettingQuery query) {
        //获得Page对象
        Page<NotifyUserSettingVO> page = query.getPage();
        List<NotifyUserSettingVO> pageList=baseMapper.findPageList(page,query);
        page.setRecords(pageList);
        return page;
    }

    /**
     * 根据id查询通知中心-用户通知配置
     * 
     * @param id 通知中心-用户通知配置主键
     * @return 通知中心-用户通知配置
     */
    @Override
    public NotifyUserSettingVO selectNotifyUserSettingById(String id)
    {
        return baseMapper.selectNotifyUserSettingById(id);
    }

    /**
     * 查询通知中心-用户通知配置列表
     * 
     * @param query 通知中心-用户通知配置
     * @return 通知中心-用户通知配置
     */
    @Override
    public List<NotifyUserSettingVO> selectNotifyUserSettingList(NotifyUserSettingQuery query)
    {
        return baseMapper.selectNotifyUserSettingList(query);
    }

    /**
     * 新增通知中心-用户通知配置
     *
     * @param newNotifyUserSettingDTO 通知中心-用户通知配置
     * @return 结果
     */
    @Override
    public Integer insertNotifyUserSetting(NewNotifyUserSettingDTO newNotifyUserSettingDTO)
    {
        NotifyUserSetting notifyUserSetting=new NotifyUserSetting();
        BeanUtils.copyProperties(newNotifyUserSettingDTO,notifyUserSetting);
        return baseMapper.insertNotifyUserSetting(notifyUserSetting);
    }

    /**
     * 修改通知中心-用户通知配置
     *
     * @param updateNotifyUserSettingDTO 通知中心-用户通知配置
     * @return 结果
     */
    @Override
    public Integer updateNotifyUserSetting(UpdateNotifyUserSettingDTO updateNotifyUserSettingDTO)
    {
        NotifyUserSetting notifyUserSetting=new NotifyUserSetting();
        BeanUtils.copyProperties(updateNotifyUserSettingDTO,notifyUserSetting);
        return baseMapper.updateNotifyUserSetting(notifyUserSetting);
    }

    /**
     * 删除通知中心-用户通知配置信息
     * 
     * @param id 通知中心-用户通知配置主键
     * @return 结果
     */
    @Override
    public Integer deleteNotifyUserSettingById(String id)
    {
        return baseMapper.deleteNotifyUserSettingById(id);
    }

    @Override
    public List<NotifyUserSettingVO> batchQuery(NotifyUserSettingQuery query) {
        return baseMapper.batchQuery(query);
    }

    @Override
    public NotifyUserSettingVO selectNotifyUserSetting(String targetType,String act,String userId) {
        return baseMapper.selectNotifyUserSetting(targetType,act,userId);
    }


    @Override
    public List<UserSettingVO>  getUserNotifySetting(String currUserId) {
        List<UserSettingVO> result=new ArrayList<>();
        List<UserNotifySettingVO> usersets=null;
        //先查询系统默认配置,与用户自定义配置比较，合并出最终配置
        List<UserNotifySettingVO>  defalutList=baseMapper.getUserNotifySetting("-1");
        List<UserNotifySettingVO> useSetList= baseMapper.getUserNotifySetting(currUserId);
        //两种情况：1、如果用户未进行自定义配置，则直接返回系统默认配置；2、用户配置项，少于系统默认配置项，则合并
        if(useSetList==null||useSetList.size()==0){
            usersets=defalutList;
        }else if(useSetList.size()<defalutList.size()){
            usersets=new ArrayList<>();
            for (UserNotifySettingVO defaultVo:defalutList){
                Boolean isExist=false;
                String type=defaultVo.getTargetType();
                String act=defaultVo.getAct();
                for (UserNotifySettingVO userSetVo:useSetList){
                    if(type.equals(userSetVo.getTargetType())&&act.equals(userSetVo.getAct())){
                        usersets.add(userSetVo);
                        isExist=true;
                        break;
                    }
                }
                if(!isExist){
                    usersets.add(defaultVo);
                }
            }

        }else if(useSetList.size()==defalutList.size()){
            usersets=useSetList;
        }
        Map<String,List<UserNotifySettingVO>>  setGroup=usersets.stream().collect(Collectors.groupingBy(UserNotifySettingVO::getTargetType));
        setGroup.forEach((key,value)->{
            UserSettingVO settingVO=new UserSettingVO();
            settingVO.setTargetType(key);
            UserTargetVO userTargetVO=targetTypeInfo.get(key);
            settingVO.setTargetTypeDesc(userTargetVO.getDesc());
            settingVO.setActs(value);
            result.add(settingVO);
        });
        return result;
    }

    @Override
    public Integer userNotifySetting(UserNotifySetDTO params) {
        Integer result=0;
        //根据参数查询配置
        String targetType=params.getTargetType();
        String act=params.getAct();
        String currUserId=params.getCurrUserId();
        if("-1".equals(currUserId)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"currUserId");
        }
        String channel=params.getChannel();
        Boolean isOpen=params.getIsOpen();
        NotifyUserSettingVO notifyUserSettingVO=baseMapper.selectNotifyUserSetting(targetType,act,currUserId);
        //存在则更新，不存在，则新增
        if(notifyUserSettingVO==null){
          //查询默认配置
            NotifyUserSettingVO defaultSettingVO=baseMapper.selectNotifyUserSetting(targetType,act,"-1");
            if(defaultSettingVO==null){
                throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"targetType or act");
            }
            String actDesc=defaultSettingVO.getActDesc();
            JSONObject setting =defaultSettingVO.getSetting();
            JSONObject channelSet=setting.getJSONObject(channel);
            channelSet.put("is_open",isOpen);
            setting.put(channel,channelSet);
            NotifyUserSetting userSetting=new NotifyUserSetting();
            userSetting.setSetting(setting);
            userSetting.setTargetType(targetType);
            userSetting.setAct(act);
            userSetting.setActDesc(actDesc);
            userSetting.setUserId(currUserId);
            userSetting.setId(null);
            userSetting.setObjectId(IdUtil.fastSimpleUUID());
            userSetting.setCreatedDate(new Date());
            userSetting.setLastModifiedDate(null);
            result=baseMapper.insert(userSetting);
        }else{
            JSONObject setting =notifyUserSettingVO.getSetting();
            JSONObject channelSet=setting.getJSONObject(channel);
            channelSet.put("is_open",isOpen);
            setting.put(channel,channelSet);
            NotifyUserSetting userSetting=new NotifyUserSetting();
            userSetting.setSetting(setting);
            userSetting.setLastModifiedDate(new Date());
            LambdaUpdateWrapper<NotifyUserSetting> updateWrapper = new UpdateWrapper<NotifyUserSetting>().lambda();
            updateWrapper.eq(NotifyUserSetting::getObjectId, notifyUserSettingVO.getObjectId());
            result=baseMapper.update(userSetting,updateWrapper);
        }
        return result;
    }


    @Override
    public boolean userSendPrivateEnable(UserSendPrivateEnableDTO params) {
        boolean result=false;
        String receiverId=params.getReceiverId();
        String currUserId=params.getCurrUserId();
        //自己不能给自己发送私信
        if(receiverId.equals(currUserId)){
            return false;
        }
        //是否可以给系统用户发送私信，根据配置
        if(receiverId.equals(systemUserProperties.getId())){
            return systemUserProperties.getIsAllow();
        }
        //查询用户配置
        JSONObject setting=null;
        NotifyUserSettingVO notifyUserSettingVO=baseMapper.selectNotifyUserSetting(CommonConstants.USER_TARGET_TYPE,CommonConstants.USER_MESSAGE_ACT,receiverId);
        //存在则更新，不存在，则新增
        if(notifyUserSettingVO==null) {
            //查询默认配置
            NotifyUserSettingVO defaultSettingVO = baseMapper.selectNotifyUserSetting(CommonConstants.USER_TARGET_TYPE,CommonConstants.USER_MESSAGE_ACT, "-1");
            if (defaultSettingVO != null) {
                setting=defaultSettingVO.getSetting();
            }
        }else{
            setting=notifyUserSettingVO.getSetting();
        }
        if(setting!=null){
            for (Integer i=30;i>=10;){
                String key=i.toString();
                JSONObject jsonObject=setting.getJSONObject(key);
                Boolean isOpen=jsonObject.getBoolean(CommonConstants.IS_OPEN);
                if(isOpen){
                    try {
                        UserFansCheckDTO checkParams=new UserFansCheckDTO();
                        switch (key){
                            case CommonConstants.USER_MESSAGE_10:
                                //查询当前用户是否是接收用户的已关注的人
                                checkParams.setFrUserId(receiverId);
                                checkParams.setToUserId(currUserId);
                                Boolean isFans=systemFeignClient.fansCheck(checkParams);
                                if(isFans){
                                    result=true;
                                }
                                break;
                            case CommonConstants.USER_MESSAGE_20:
                                //查询当前用户是否关注接收用户
                                checkParams.setFrUserId(currUserId);
                                checkParams.setToUserId(receiverId);
                                Boolean isFollows=systemFeignClient.fansCheck(checkParams);
                                if(isFollows){
                                    result=true;
                                }
                                break;
                            case CommonConstants.USER_MESSAGE_30:
                                result=true;
                                break;
                        }
                    }catch (Exception e){
                        result=false;
                        e.printStackTrace();
                        log.error("userSendPrivateEnable user fans check error!");
                    }
                }
                if(result){
                    //只要有一个为真，则终止返回结果
                    break;
                }
                i=i-10;
            }
        }
        return result;
    }
}
